package com.sso.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String _COOKIENAME = "SSO" ;
	private ConcurrentMap SSOMap;
    public MainServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		execute(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		execute(request,response);
	}

	private void execute(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		String rs = "";
		try {
			String method = request.getParameter("method");
			String tourl = request.getParameter("tourl");
			if("login".equals(method)){
				session.setAttribute("tourl", tourl);
				request.getRequestDispatcher("login.jsp").forward(request,response);
			}else if("getFlag".equals(method)){
				String cookiename = request.getParameter("cookiename");
				System.out.println("---------cookiename:"+cookiename);
				System.out.println("---------SSOMap.size():"+SSOMap.size());
				if(cookiename!=null&&SSOMap!=null&&SSOMap.size()>0){
					String value = SSOMap.get(cookiename).toString();
					if(value != null){
						rs = value;
					}else{
						rs = "nologin";
					}
				}else{
					rs = "nologin";
				}
			}else if("logincheck".equals(method)){
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				tourl = session.getAttribute("tourl").toString();
				if("t".equals(username)&&"123".equals(password)){
					SSOMap.put(_COOKIENAME, "t");
					System.out.println("--------tourl:"+tourl);
					response.sendRedirect(tourl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			PrintWriter pw = response.getWriter();
			pw.write(rs);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	@Override
	public void init() throws ServletException {
		SSOMap = new ConcurrentHashMap<String,Object>();
	}
}
